package com.hjp.security.springboot.exception;

import com.hjp.security.springboot.common.CommonException;
import com.hjp.security.springboot.common.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * 统一异常处理
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(AccessDeniedException.class)
    @ResponseBody
    public Response accessDeniedExceptionError(AccessDeniedException e) {
        log.error("业务异常:", e);
        String message = "请联系管理员，开通权限！";
        CommonException exception = new CommonException(Response.FAILED_CODE, message);
        return Response.builderFailed(exception);
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseBody
    public Response NoHandlerFoundExceptionError (NoHandlerFoundException  e) {
        log.error("系统异常:", e);
        CommonException exception = new CommonException("404", e.getMessage());
        return Response.builderFailed(exception);
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Response ExceptionError(Exception e) {
        log.error("系统异常:", e);
        String message = "出错了！";
        CommonException exception = new CommonException("ERROR", message);
        return Response.builderFailed(exception);
    }
}
